package com.tienphong.clipxonxao;

import java.net.URI;
import java.net.URISyntaxException;

import org.json.JSONObject;

import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.parse.ParseAnalytics;

public class MainActivity extends Activity implements OnRefreshListener {
	private ProgressBar progressBar1;
	WebView webView;
	public String urlLoad = "";
	public String homePage = "http://clipxonxao.vn/";
	private boolean isLoad = true;
	private PullToRefreshLayout mPullToRefreshLayout;
	private ImageView btnShare;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ParseAnalytics.trackAppOpened(getIntent());

		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		progressBar1 = (ProgressBar) findViewById(R.id.loadding);
		webView = (WebView) findViewById(R.id.webView1);
		settingWebview(webView);

		try {
			Intent intent = getIntent();
			Bundle extras = intent.getExtras();
			if (extras != null) {
				JSONObject json = new JSONObject(intent.getExtras().getString(
						"com.parse.Data"));
				urlLoad = json.getString("url");
				Log.d("urlData", urlLoad);

				if (isValidURI(urlLoad)) {
					webView.loadUrl(urlLoad);
				} else {
					webView.loadUrl(homePage);
				}
				isLoad = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (isLoad) {

			webView.loadUrl(homePage);

		}
		mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout);
		ActionBarPullToRefresh.from(this).allChildrenArePullable()
				.listener(this).setup(mPullToRefreshLayout);

		btnShare = (ImageView) findViewById(R.id.btnShare);
		btnShare.setVisibility(View.GONE);
		btnShare.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				shareButton(MainActivity.this);
			}
		});

	}

	public void shareButton(Context context) {
		Intent textShareIntent = new Intent(Intent.ACTION_SEND);
		textShareIntent.putExtra(Intent.EXTRA_TEXT, urlLoad);
		textShareIntent.setType("text/plain");
		startActivity(Intent.createChooser(textShareIntent, "Clip Xôn Xao - ClipXonXao.vn"));
	}

	public boolean isOnline(Activity activity) {
		ConnectivityManager connectivity = (ConnectivityManager) activity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null)
				for (int i = 0; i < info.length; i++)
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
		}
		return false;
	}

	public boolean isValidURI(String uriStr) {
		try {
			URI uri = new URI(uriStr);
			return true;
		} catch (URISyntaxException e) {
			return false;
		}
	}

	@Override
	public void onBackPressed() {
		if (!urlLoad.equalsIgnoreCase(homePage)) {

			webView.loadUrl(homePage);

		} else {
			webView.stopLoading();
			finish();
		}

	}

	private void settingWebview(WebView webview_fbview) {
		webview_fbview.getSettings().setJavaScriptEnabled(true);
		webview_fbview.setLongClickable(false);

		webview_fbview.getSettings().setLoadWithOverviewMode(true);
		webview_fbview.getSettings().setJavaScriptCanOpenWindowsAutomatically(
				true);

		webview_fbview.getSettings().setUseWideViewPort(true);
		webview_fbview.requestFocus(View.FOCUS_DOWN);
		webview_fbview.setPadding(0, 0, 0, 0);
		webview_fbview.setWebViewClient(new webViewClient());
		webview_fbview.setWebChromeClient(new webChromeClient());
		webview_fbview.setInitialScale(100);
		webview_fbview.clearCache(true);
		webview_fbview.clearHistory();
		webview_fbview.getSettings().setDefaultFontSize(14);
		webview_fbview.addJavascriptInterface(new JavaScriptInterface(this),
				"Android");
		webview_fbview.setVisibility(View.VISIBLE);

		webview_fbview.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				if (progress < 50 && progressBar1.getVisibility() == View.GONE
						&& urlLoad.equalsIgnoreCase(homePage)) {
					progressBar1.setVisibility(View.VISIBLE);
				}
				if (progress >= 50) {
					progressBar1.setVisibility(View.GONE);
					if(!urlLoad.equalsIgnoreCase(homePage)){
						btnShare.setVisibility(View.VISIBLE);
					}else{
						btnShare.setVisibility(View.GONE);
					}
				}
			}
		});
	}

	public class JavaScriptInterface {
		Context mContext;

		// Instantiate the interface and set the context
		JavaScriptInterface(Context c) {
			mContext = c;
		}

		// using Javascript to call the finish activity
		public void closeMyActivity() {
			// finish();
		}
	}

	private class webChromeClient extends WebChromeClient {

		// display alert message in Web View
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				JsResult result) {
			new android.app.AlertDialog.Builder(view.getContext())
					.setMessage(message).setCancelable(true).show();
			result.confirm();
			return true;
		}
	}

	public void getDialogConFirm(Activity activity, String mes) {
		final Dialog dialog = new Dialog(activity);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.background_card);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(R.layout.dialogconfirm);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay()
				.getMetrics(displaymetrics);
		int width = displaymetrics.widthPixels;
		dialog.getWindow().setLayout(5 * width / 6, LayoutParams.WRAP_CONTENT);

		dialog.show();
		TextView lblMess = (TextView) dialog.findViewById(R.id.lblMessage);
		lblMess.setText(Html.fromHtml(mes));

		Button btnAccept = (Button) dialog.findViewById(R.id.btnAccept);

		btnAccept.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
				dialog.dismiss();
				finish();

			}
		});
		Button btnNo = (Button) dialog.findViewById(R.id.btnNo);

		btnNo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
				dialog.dismiss();

			}
		});
	}

	private class webViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			progressBar1.setVisibility(View.GONE);
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			webView.loadUrl("file:///android_asset/load.htm");
			getDialogConFirm(MainActivity.this,
					"Vui lòng kiểm tra lại kết nối Internet!");

		}

		@Override
		public void onPageFinished(WebView view, String urlCurent) {
			Log.d("url", urlCurent);
			urlLoad = urlCurent;
			
			if (mPullToRefreshLayout.isRefreshing()) {
				mPullToRefreshLayout.setRefreshComplete();
			}
			super.onPageFinished(view, urlLoad);
		}
	}

	@Override
	public void onRefreshStarted(View view) {
		// Here we just reload the webview
		webView.reload();

	}

}
